<template>
	<view>
		<view>
			<list ref="list"></list>
			<view class="bottom-fixed">
				<view @tap="onBindtapCreate">
					<uni-icons custom-prefix="iconfont" type="icon-zengjia1" size="60" color="#FF0025"></uni-icons>
					<view class="add-group">{{$t('General.family.addNewHome')}}</view>
				</view>
			</view>
		</view>
        <j-modal :value="value" @ok="submit" @cancel="() => {value = false}" @mask="() => {value = false}">
            <template slot="content">
                <form>
                <input :focus="focus" :placeholder="$t('General.family.familyPla')" name="groupName" v-model="groupName"
                       class="form-control" style="background: #f6f6f6;text-align: left" />
                </form>
            </template>
        </j-modal>
	</view>
</template>

<script>
	import list from './list/list';
    import {isEmojiCharacter} from "@/utils/util";
	export default {
		components: {
			list
		},
		data() {
			return {
				focus: false,
				groupName: '',
				disabled:false,
                value: false,
			};
		},
        onShow() {
            uni.setNavigationBarTitle({
                title: this.$t('General.family.homeManagement')
            })
        },
		onLoad: function(options) {
			this.getClipboardData()
			// #ifdef H5
			this.$nextTick(()=>{
				this.$refs.list.getUserGroupListByPage('Refresh')
			})
			// #endif
		},
		onPullDownRefresh: function() {
			if (this.$refs.list) {
				this.$refs.list.getUserGroupListByPage('Refresh')
			}
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			// 创建家庭
			onBindtapCreate(ev) {
				// this.$refs.popup.open()
                this.value = true
				this.groupName = ''

				setTimeout(() => {
					this.focus = true
				}, 350);
			},

			// 表单提交
			submit(ev) {
				if (this.groupName.replace(/\s/g, '') === '') {
					uni.showToast({
						title: this.$t('General.family.msg1'),
                        icon: 'none'
					});
					return;
				}
                if(this.groupName.length == 2 && isEmojiCharacter(this.groupName)) {
                    uni.showToast({
                        title: this.$t('General.family.msg2'),
                        icon:'none'
                    });
                    return;
                }
				if(this.groupName.length<2 || this.groupName.length>50 ){
					uni.showToast({
						title: this.$t('General.family.msg2'),
						icon:'none'
					});
					return;
				}
                const list = uni.getStorageSync('groupList')
                console.log(list, '这是一个list')
                const arr = list.filter(item => item.groupName === this.groupName)
                console.log(arr)
                if(arr.length > 0) {
                    uni.showToast({
                        title: this.$t('General.family.msg3'),
                        icon: 'none',
                    });
                    return;
                }


				let data = {
					groupName: this.groupName
				};
				uni.showLoading({
					title:this.$t('General.family.msg4'),
				})
				this.value = false
				this.disabled = true
				getApp().globalData.api.addUserGroup(data, (result) => {
					console.log('添加用户组=========',result);
					uni.hideLoading()
					this.disabled = false
					if(result.data.code == 2000){
						// this.$refs.popup.close()
                        this.value = false
						this.focus = false
						this.groupName = ''
						this.$refs.list.getUserGroupListByPage('add');
					}else if(result.data.code == '-91005'){
						uni.showToast({
							title:this.$t('General.family.msg5'),
							icon:'none'
						})
					}else{
						uni.showToast({
							title:result.data.msg,
							icon:'none'
						})
					}
				},false,false);
			},

			change(ev) {
				console.log('change:', ev);
			},
			maskClick(ev) {
				console.log('maskClick', ev);
				this.focus = false
			},

			// 是否有邀请码，并且被加入用户组
			getClipboardData() {
				uni.getClipboardData({
					success: res => {
						console.log('获取剪切板邀请码：', res)
						uni.hideToast();
						if (res.errMsg === 'getClipboardData:ok' && res.data !== '') {
							// this.decodeKey(res.data)
							if(res.data.includes('请长按复制邀请码，打开app加入用户组')){
								if(uni.getStorageSync('inviteCode')!=res.data.split(':')[1]){
									this.decodeKey(res.data)
									uni.setStorageSync('inviteCode',res.data.split(':')[1])
								}
							}
						}
					}
				})
			},
			// 解析邀请口令
			decodeKey(key) {
				const data = {
					key: key
				}
				// 解析邀请码
				getApp().globalData.api.decodeKey(data, result => {
					console.log('解析邀请码：', result);
					if (result.data.code === 2000) {
						// 用户操作是否加入家庭组
						uni.showModal({
							title: '提示',
							content: `是否加入家庭组【${result.data.data.userGroupName}】`,
							success: res => {
								if (res.confirm) {
									console.log('用户点击确定')
									this.addUser(key)
								} else if (res.cancel) {
									console.log('用户点击取消')
								}
							},
							fail(err) {
								console.log('error:', err);
							},
							complete() {
								uni.setClipboardData({
									data: ' ',
									success(res) {
										uni.hideToast()
										console.log('清空剪切板1：', res);
									}
								})
							}
						})
					} else {
						uni.showToast({
							title: result.data.msg,
							duration: 2000,
							icon:'none',
							success: (res) => {
								setTimeout(() => {
									uni.setClipboardData({
										data: ' ',
										success(res) {
											uni.hideToast()
											console.log('清空剪切板2：', res);
										},
										fail: (err) => {
											console.log('清空剪切板error',err);
										}
										
									})
								}, 1000)
							}
						});
					}
				})
			},
			// 加入家庭
			addUser(key) {
				const params = {
					userName: uni.getStorageSync('userInfo').nickName || uni.getStorageSync('userInfo').nickname || uni.getStorageSync('userInfo').username,
					key: key,
				}
				// 添加用户到家庭组
				getApp().globalData.api.addUser(params, result => {
					console.log('当前用户加入到用户组:', result);
					this.$refs.list.getUserGroupListByPage()
				})
			},
		}
	};
</script>
<style lang="scss">
    .popupName {
        /deep/ .uni-popup__wrapper {
            //top: -100rpx;
            top: -100rpx;
        }
    }
	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;
	}

	.form .form-item {
		margin-top: 20rpx;
	}

	.form .form-title {
		text-align: center;
		margin-bottom: 40rpx;
		font-weight: bold;
	}

	.form .form-item .form-control {
		background: #efefef;
	}
	.add-group{
		font-size: 24rpx;
	}
</style>
